package org.apache.dubbo.demo.example.eg4;

import java.util.HashMap;
import java.util.Map;
import org.apache.dubbo.common.Constants;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.rpc.Filter;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.Result;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.rpc.RpcResult;



@Activate(group = Constants.PROVIDER, value = "resolver")
public class ExceptionResolver implements Filter {

  @Override
  public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
    Result result = invoker.invoke(invocation);
    if (result.getException() instanceof BusinessException) {
      BusinessException exception = (BusinessException) result.getException();
      result = new RpcResult(wrapException(exception));
    }

    return result;
  }

  private Map<String, Object> wrapException(BusinessException exception) {
    Map<String, Object> result = new HashMap<>();
    result.put("errorCode", exception.getErrorCode());
    result.put("errorMsg", exception.getMessage());
    return result;
  }
}
